package com.aaa.aop;

import com.aaa.entity.ResultMsg;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Aspect
public class OauthToken {
    /**
     * 环绕通知
     *  postAccessToken:  /oauth/token
     *1. 授权码（authorization-code）：先返回授权码
     *  * 2. 隐藏式（implicit）：返回令牌信息
     *  * 3. 密码式（password）：返回令牌信息
     *  * 4. 客户端凭证（client credentials）：返回令牌信息
     */


    @Around("execution(public * org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object tokenHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object proceed = joinPoint.proceed();// 执行接口
        Map<String, Object> map = (Map<String, Object>) args[1];
        String grant_type = map.get("grant_type").toString();
        if ("authorization_code".equals(grant_type)) {
            // 直接返回结果
            return proceed;
            } else {
            // 封装令牌格式
            Object body = ((ResponseEntity) proceed).getBody();
            // {code:,message:,data:}
            ResultMsg resultMsg = ResultMsg.success(body); return new ResponseEntity<ResultMsg>(resultMsg, HttpStatus.OK); }
    }
}
